package com.jdk.demo.thread.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

// 当一个线程依赖另一个线程时，可以使用 thenApply 方法来把这两个线程串行化。
//public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
//public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
//public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
//Function<? super T,? extends U>
//T：上一个任务返回结果的类型
//U：当前任务的返回值类型

// thenApply 只可以执行正常的任务，任务出现异常则不执行 thenApply 方法
public class ThenApplyDemo {

	public static void main(String[] args) throws InterruptedException {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
        CompletableFuture cf = CompletableFuture.supplyAsync(() -> { //实现了Supplier的get()方法
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("supplyAsync " + Thread.currentThread().getName());
            return 100;
        }, executorService)
		.thenApply(new Function<Integer, Long>() {
	        @Override
	        public Long apply(Integer t) {
	            long result = t + 5;
	            System.out.println("result2="+result);
	            return result;
	        }
	    });

        System.out.println(Thread.currentThread().getName());
        while (true) {
            if (cf.isDone()) {
                System.out.println("CompletedFuture...isDown " + Thread.currentThread().getName());
                break;
            }
            Thread.sleep(5000);
        }
	}

}
